﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Utilities;

namespace ContentTypeCustomForms.CONTROLTEMPLATES.MyFolder
{
    public partial class MyUserControl : UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (SPContext.Current.FormContext.FormMode == SPControlMode.Edit) LoadFieldsValues();
                else myTextBox.Text = "Today is " + DateTime.Now.DayOfWeek + ".";
            }
            else
            {
                SPUtility.ValidateFormDigest();
                SetFieldsValues();
            }
        }
        private void SetFieldsValues()
        {
            foreach (object field in SPContext.Current.FormContext.FieldControlCollection)
            {
                TextField tField = field as TextField;
                if (null != tField && "MyField" == tField.FieldName)
                {
                    tField.Value = myTextBox.Text;
                    tField.ItemFieldValue = myTextBox.Text;
                }
            }
        }
        private void LoadFieldsValues()
        {
            string myFieldValue = (string)SPContext.Current.ListItem["MyField"];
            myTextBox.Text = myFieldValue;
        }
    }
}